package com.kuang.blog.util;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.kuang.blog.entity.User;
import com.kuang.blog.exception.AllException;
import io.jsonwebtoken.*;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Optional;
import java.util.UUID;

@Component
public class JwtUtils {
    //时间转化ms
    private long time = 1000 * 60 * 60 * 24;
    private String signatrue = "zhonghaoJwt";

    /**
     * jwt加密
     * 设置Header-payload-singnature（作者）
     */
    public String jwtEncrypt(User user) {
        JwtBuilder builder = Jwts.builder();
        String token = builder.setHeaderParam("type", "jwt")
                .setHeaderParam("Algorithm", "HS256")
                //payload
                .claim("username", user.getUsername())
                .claim("password", user.getPassword())
                .claim("role", "system")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(user.getId().toString())
                //singnatrue
                .signWith(SignatureAlgorithm.HS256, signatrue)
                .compact();
        return token;

    }

    /**
     * jwt解密
     * jwtParser.setSigningKey(signatrue).parseClaimsJws(token);得到信息
     */
    public Claims decodeJwt(String token) {
        JwtParser jwtParser = Jwts.parser();
        Jws<Claims> claimsJws;
        try {
            claimsJws = jwtParser.setSigningKey(signatrue).parseClaimsJws(token);
        } catch (Exception e) {
            throw new AllException("token错误");
        }
        Claims body = claimsJws.getBody();
        return body;
    }

    /**
     * 获取请求的token
     */
    public static String getRequestToken(HttpServletRequest httpRequest) {

        //从header中获取token
        String token = httpRequest.getHeader("token");
        //如果header中不存在token，则从参数中获取token
        if (token == null) {
            token = httpRequest.getParameter("token");
        }
        return token;
    }

}
